<template>
<!-- 新增/编辑用户弹框 -->
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="close" :close-on-click-modal="false" width="60%">
    <el-form inline :rules="userRules" :model="userForm" ref="userRef"  label-position="right" >
        <el-form-item label="姓名:" prop="nickname">
         <el-input v-model="userForm.nickname" placeholder="请输入姓名" maxlength = 10></el-input>
        </el-form-item>
        <el-form-item label="学号:" prop="username">
           <el-input v-model.number="userForm.username" placeholder="请输入学号" maxlength = 10></el-input>
        </el-form-item>
        <el-form-item label="班级:" prop="grade">
           <el-input v-model="userForm.grade" placeholder="请输入班级" maxlength = 10></el-input>
        </el-form-item>
        <el-form-item label="性别:" class="gender" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label= 1>男</el-radio>
            <el-radio :label= 2>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机:" prop="mobile">
         <el-input v-model.number="userForm.mobile" placeholder="请输入电话" type="tel" maxlength = 11></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
           <el-input v-model="userForm.email" placeholder="请输入邮箱" maxlength = 30></el-input>
        </el-form-item>
        <el-form-item label="设为管理员:" prop="role">
          <el-checkbox v-model="userForm.role" true-label= "1" false-label= "2"></el-checkbox>
        </el-form-item>
    </el-form>
     <span slot="footer" class="dialog-footer">
        <el-button @click="close()" :loading="buttonLoading">取 消</el-button>
        <el-button v-if="curId" type="primary" @click="edit()" :loading="buttonLoading">确 定</el-button>
        <el-button v-else type="primary" @click="add()" :loading="buttonLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
 data() {
   //验证手机规则
    const checkPhone = (rule, value, callback) => {
      if (value === "" || value === null) {
        return callback();
      }
      const regPhone = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
      if (regPhone.test(value)) {
        //合法手机
        return callback();
      }
      callback(new Error("请输入合法手机号"));
    };
    return {
      dialogVisible: false,
      buttonLoading: false,
      loading: false,
      title: "新增用户",
      userForm:{
        username:'',
        gender:'',
        nickname:'',
        grade:'',
        mobile:'',
        role: '2' ,
        email:'',
      },
      userRules: {
        nickname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        username: [{ required: true, message: "请输入学号", trigger: "blur"},
                   { type: 'number', message: '学号必须为数字值'}
                   ],
        gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
        grade: [{ required: true, message: "请输入班级", trigger: "blur" }],
        mobile: [{ validator: checkPhone, trigger: "change" }],
        email: [{ type: 'email', message: '请输入正确的邮箱格式', trigger: "blur"}],
      }
    };
  },
  props:{
    curId: {},
  },
  watch:{
    //监听curId判断是编辑还是新增
    dialogVisible(val){
      if(val){
        console.log(this.curId,333333)
        if (this.curId) {
          this.getDetail(this.curId);
        }
      }
    }
  },
  methods:{
    //打开
    open() {
      this.dialogVisible = true;
    },
    //关闭
    close() {
      this.dialogVisible = false;
      this.$refs.userRef.resetFields();
      this.userForm = {}
      this.userForm.mobile = ''
      this.title = "新增用户"
    },
    //新增
    add() {
      this.$refs.userRef.validate( async valid => {
        if (!valid) return 
        this.buttonLoading = true;
        await this.$http.post("user/register",this.userForm)
        .then((res) => {
          console.log(res)
          if(res.status === 200){
            this.close();
            this.$message.success("新增用户成功!");
            this.$emit("getListData");
          }     
          this.buttonLoading = false;
        })
        .catch((err) => { 
          this.buttonLoading = false;
          this.$message.error(err.response.data.message)
        });
      });
    },
    //详情
    getDetail(_id){
      console.log(_id,77)
      this.loading = true;
      this.$http.get("user/detail/" + _id)
        .then((res) => {
          console.log(res,456)
          if(res.status === 200){
            this.userForm = res.data.data
            this.userForm.username = parseInt(res.data.data.username)
            delete this.userForm.password
            this.loading = false;
            this.title = "编辑用户";
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error("获取信息失败！")
        })
    },
    //编辑
    edit(_id) {
      this.$refs.userRef.validate( async valid => {
        if (!valid) return 
        _id = this.curId
        console.log(_id,this.curId,222222222)
        this.buttonLoading = true;
        await this.$http.put("user/update/" + _id, this.userForm)
        .then((res) => {
          console.log(res)
          if(res.status === 200){
            this.close();
            this.$message.success("编辑用户成功!");
            this.$emit("getListData");
          }     
          this.buttonLoading = false;
        })
        .catch((err) => { 
          this.buttonLoading = false;
          this.$message.error("编辑用户失败！")
        });
      });
    },

  },
};
</script>

<style lang="scss" scoped>
.gender{
  margin-right: 40px;
}
</style>